package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 分类业务实现类
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 自己的业务方法，实现逻辑
     * 检查是否有菜品或套餐
     * 有，不删除   没有可以
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //构建菜品查询条件，进行业务查询
        LambdaQueryWrapper<Dish> queryWrapperDish = new LambdaQueryWrapper();

        queryWrapperDish.eq(Dish::getCategoryId, id);
        int countDish = dishService.count(queryWrapperDish);

        log.info("[删除分类-分类查询菜品],count:{}", countDish);
        if (countDish > 0) {
            //不能删除
            log.info("[删除分类-分类查询菜品],有关联数据不能删除");
            //业务异常
            //throw new RuntimeException("菜品有关联数据,不能删除");
            throw new CustomException("菜品有关联数据,不能删除");
        }

        //
        LambdaQueryWrapper<Setmeal>queryWrapperSetmeal=new LambdaQueryWrapper<>();
        queryWrapperSetmeal.eq(Setmeal::getCategoryId,id);
        int countSetmeal = setmealService.count(queryWrapperSetmeal);
        log.info("[删除分类-分类查询菜品],count:{}",countSetmeal);
        if (countSetmeal > 0) {
            //不能删除
            log.info("[删除分类-分类查询菜品],有关联数据不能删除");

            //throw new RuntimeException("菜品有关联数据,不能删除");
            throw new CustomException("菜品有关联数据,不能删除");
        }
        //如果没有就能删
        //this当前对象
        this.removeById(id);
    }
}